package com.getsendsocial.GetSendSocial.Activity;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;


import com.getsendsocial.GetSendSocial.R;
import com.getsendsocial.GetSendSocial.Database.ContactAdapter;
import com.getsendsocial.GetSendSocial.Database.GetContact;
import com.getsendsocial.GetSendSocial.Util.GetTab;

import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ContactActivity extends ListActivity {

	// declare class variables
	public static ProgressDialog dialog;
	public static ArrayList<String> listContact;
	private String dest;
	private String name;
	private  ContactAdapter adapter;
	private ListView list ;


    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_activity);
        
   
		try {
			adapter = new GetContact(this,false,null).execute(getContentResolver()).get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		// display the list.
		list=(ListView)findViewById(android.R.id.list);
	    list.setAdapter(adapter);
	    list.setTextFilterEnabled(true);
	    final EditText et = (EditText) findViewById(R.id.editTextSend);

	    et.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
					adapter.getFilter().filter(arg0);
			}
	    	
	    });
	}
    @Override 
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	TextView tt = (TextView)v.findViewById(R.id.name);
    	name = tt.getText().toString();
    	if (name.equals("Inserisci Numero")){
    		final Dialog addNum = new Dialog(ContactActivity.this);
    		addNum.setContentView(R.layout.addnumber);
    		addNum.setTitle("Inserisci il numero");
    		final EditText et = (EditText)addNum.findViewById(R.id.edittextAddNumber);
    		Button b = (Button)addNum.findViewById(R.id.sendAddNumber);
    		b.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					dest = et.getText().toString();
					confirmSending();
					addNum.cancel();
				}
			});
    		addNum.show();
    	}else{
    		Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +" = ?", new String[]{name}, null);
    		final ArrayList<String> nums = new ArrayList<String>();
    		while (pCur.moveToNext()){
    			String numero=pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    			nums.add(numero);
    		}
    		pCur.close();
    	
    		if (nums.size()!=1){
    			try {
    				adapter = new GetContact(this,true,nums).execute(getContentResolver()).get();
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
    			}
    		
    		final Dialog dial= new Dialog(ContactActivity.this);
    		dial.setContentView(R.layout.chosenumber);
    		dial.setTitle("Scegli il numero:");
    		ListView lv = (ListView) dial.findViewById(android.R.id.list);
    		lv.setAdapter(adapter);
    		
    		lv.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
						TextView t = (TextView)arg1.findViewById(R.id.name);
						dest = t.getText().toString();
						dial.cancel();
			    		confirmSending();
				}
			});
    		dial.show();
    		
    }else{
    	dest = nums.get(0);
    	confirmSending();    	
    }
    	}
    }
    public void sendSms(){
        TelephonyManager telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        if (simState==TelephonyManager.SIM_STATE_READY){
        	send();
        }else{
    	    Toast.makeText(ContactActivity.this,"Controlla la tua sim!", Toast.LENGTH_LONG).show();

        }
    	
    }
    
    private void send() {
    	String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
        
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,new Intent(SENT), 0);
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this,0, new Intent(DELIVERED), 0);
        registerReceiver(new BroadcastReceiver() {

			@Override
			public void onReceive(Context arg0, Intent arg1) {
				 switch (getResultCode()) {
	                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
	                    Toast.makeText(ContactActivity.this, "Errore generico!",Toast.LENGTH_SHORT).show();
	                    break;
	                case SmsManager.RESULT_ERROR_NO_SERVICE:
	                    Toast.makeText(ContactActivity.this, "Nessun Servizio!", Toast.LENGTH_SHORT).show();
	                    break;
	                case SmsManager.RESULT_ERROR_NULL_PDU:
	                    Toast.makeText(ContactActivity.this, "PDU nulla! ",Toast.LENGTH_SHORT).show();
	                    break;
	                case SmsManager.RESULT_ERROR_RADIO_OFF:
	                    Toast.makeText(getBaseContext(), "Modalità offline. Attivala per inviare l'SMS.", Toast.LENGTH_SHORT).show();
	                    break;
	                    }
			}
        	
        }, new IntentFilter(SENT));

        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(ContactActivity.this, "Il messaggio è stato inviato correttamente!",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(ContactActivity.this, "Il messaggio non è stato inviato. Riprova!",
                            Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }, new IntentFilter(DELIVERED));
        
    	SmsManager smsMngr = SmsManager.getDefault();
        smsMngr.sendTextMessage(dest,null, GetTab.frase, sentPI, deliveredPI);
        Toast.makeText(ContactActivity.this, "Invio il messaggio. Attendi la prossima notifica" +
        		"per conoscere l'esito dell'invio.",
                Toast.LENGTH_SHORT).show();

	}
	public void confirmSending(){
    	final Dialog dialog = new Dialog(ContactActivity.this);
    	dialog.setContentView(R.layout.dialog);
    	dialog.setTitle("Conferma");
    	TextView t = (TextView) dialog.findViewById(R.id.textViewDialog);
		if (name.equals("Inserisci Numero")){
			t.setText("Confermi l'invio a " + dest +"?");
		}else{
			t.setText("Confermi l'invio a " + name + " (" + dest + ")?");
		}
    	Button siButton = (Button)dialog.findViewById(R.id.siButton);
    	final Button noButton = (Button)dialog.findViewById(R.id.noButton);
    	
    	siButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				sendSms();
				dialog.cancel();
			}
		});
    	
    	noButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				dialog.cancel();
			}
		});
		

    	dialog.show();
    }
}
